package com.ehotting.mqbd.loader.task;

import com.ehotting.eaf.core.DateHelper;
import com.ehotting.eaf.core.snow.SnowflakeUtil;
import com.ehotting.eaf.redis.service.RedisService;
import com.ehotting.mqbd.api.MQDBConstants;
import com.ehotting.mqbd.core.logger.LOGGER_KEY;
import com.ehotting.mqbd.core.manager.ConsumerNodeManager;
import com.ehotting.mqbd.core.manager.ModuleManager;
import com.ehotting.mqbd.core.manager.SolverInfoManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.refresh.ContextRefresher;
import org.springframework.scheduling.annotation.Scheduled;

import java.util.Date;

public class SolverInfoLoader {

    private static final Logger logger = LoggerFactory.getLogger(SolverInfoLoader.class);

    @Autowired
    private ContextRefresher contextRefresher;

    private SolverInfoManager solverInfoManager;
    @Autowired
    private ConsumerNodeManager consumerNodeManager;

    private RedisService redisService;

    private ModuleManager moduleManager;

    @Scheduled(initialDelay=20000, fixedRate=10000)
    public void reload(){
        MDC.put(LOGGER_KEY.TRACE_ID, SnowflakeUtil.nextId64());
        try{
            String time = DateHelper.toSeparatorStringyyyyMMddHHmmss(new Date());
            boolean lock = redisService.checkLock(MQDBConstants.REDIS_LOCK_KEY_RELOAD,time,1000L*30);
            if(lock == false){
                logger.info("Reload is locked,return.");
                return;
            }
            logger.info("Start reload:{}",time);

            new Thread(() -> contextRefresher.refresh()).start();
            logger.info("___________________LOAD MODULE___________________");
            moduleManager.loadModule();
            logger.info("___________________LOAD LOADER___________________");
            solverInfoManager.loadSolver();
            logger.info("___________________CLEAR OFFLINE CONSUMER ___________________");
            consumerNodeManager.clearOffLineConsumer();
        }catch (Exception e){
            logger.error("reload()",e);
        }finally {
            MDC.clear();
        }


    }


    public void setSolverInfoManager(SolverInfoManager solverInfoManager) {
        this.solverInfoManager = solverInfoManager;
    }

    public void setModuleManager(ModuleManager moduleManager) {
        this.moduleManager = moduleManager;
    }

    public void setRedisService(RedisService redisService) {
        this.redisService = redisService;
    }
}
